package com.luych.toolbox.common.xml;

import java.util.*;

public class XmlNode {

    private final String name;
    private XmlNode parent;
    private Map<String, String> attrs = new LinkedHashMap<>();
    private List<XmlNode> children = new ArrayList<>();
    private String value;

    public XmlNode(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public XmlNode getParent() {
        return parent;
    }

    public void setParent(XmlNode parent) {
        this.parent = parent;
    }

    public Map<String, String> getAttrs() {
        return attrs;
    }

    public void setAttrs(Map<String, String> attrs) {
        this.attrs = attrs;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public List<XmlNode> getChildren() {
        return children;
    }

    public void setChildren(List<XmlNode> children) {
        this.children = children;
    }

    public XmlNodeReader safeRead() {
        return new XmlNodeReader(Collections.singletonList(this));
    }

    public XmlNodeWriter safeWrite() {
        return new XmlNodeWriter(this);
    }

    public boolean isAttributeEmpty(String... ignores) {
        Set<String> ketSet = new HashSet<>(this.attrs.keySet());
        ketSet.removeIf(Arrays.asList(ignores)::contains);
        return ketSet.isEmpty();
    }

    public boolean isValueEmpty() {
        return this.children.isEmpty() && (this.value == null || this.value.equals(""));
    }

    public boolean isEmpty(String... ignoreAttributes) {
        return this.isAttributeEmpty(ignoreAttributes) && this.isValueEmpty();
    }

    public String getPath() {
        XmlNode curr = this;
        StringBuilder path = new StringBuilder(curr.getName());
        while (curr.parent != null) {
            curr = curr.parent;
            path.insert(0, curr.getName() + ".");
        }
        return path.toString();
    }
}
